<?php

namespace App\Http\Controllers\Api;

use App\Models\UserModel;
use App\Utils\Message;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends BaseController
{

    /**
     * 用户注册
     *
     * @param Request $request
     * @param UserModel $userModel
     * @return void
     */
    public function register(Request $request, UserModel $userModel)
    {
        $user['phone'] = $request->phone;
        $user['password'] = $request->password;
        $user['gid'] = 1;

        if (empty($user['phone'])) {
            return Message::show_message(false, '手机号码不能为空');
        }

        if (empty($user['password'])) {
            return Message::show_message(false, '登录密码不能为空');
        }

        if (strlen($user['password']) < 6) {
            return Message::show_message(false, '登录密码长度至少6位');
        }

        if ($userModel->where(['phone' => $user['phone']])->exists()) {
            return Message::show_message(false, '手机号码已被使用，请联系客户找回');
        }

        // 加密密码
        $user['password'] = Hash::make($user['password']);

        // 写入数据库
        DB::beginTransaction();

        try {
            // 写入数据库
            $userInfo = $userModel->create($user);

            DB::commit();
            return Message::show_message(true, '注册成功');
            // 置用户状态为已登录
            // $token = Auth::guard('api')->tokenById($userInfo->uid);
        } catch (Exception $error) {
            DB::rollBack();
            return Message::show_message(false, $error->getMessage());
        }
    }

    /**
     * 用户登录
     *
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        $user['phone'] = $request->phone;
        $user['password'] = $request->password;

        if (empty($user['phone'])) {
            return Message::show_message(false, '手机号码不能为空');
        }

        if (empty($user['password'])) {
            return Message::show_message(false, '登录密码不能为空');
        }

        if (strlen($user['password']) < 6) {
            return Message::show_message(false, '登录密码长度至少6位');
        }

        if (!$token = Auth::guard('api')->attempt($user)) {
            return Message::show_message(false, 'Unauthorized!!!!!!', [], 401);
        }

        return Message::show_message(true, '登录成功', [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => Auth::guard('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     * 获取个人信息
     *
     * @return void
     */
    public function get_self_info()
    {
        $user = Auth::guard('api')->user();
        if(empty($user)) {
            return Message::show_message(false, '用户信息无效');
        }
        return Message::show_message(true, 'success', $user);
    }
}
